package com.blockchain.console.servlets.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.math.BigDecimal;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.DatatypeConverter;

import com.blockchain.console.service.financial.entity.Balance;
import com.blockchain.console.service.financial.entity.PtqbEntity;
import com.blockchain.util.HttpRequest;
import com.blockchain.util.StringHelper;
import com.blockchain.util.parser.BigDecimalParser;

import net.sf.json.JSONObject;

public class BtcUtil implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Swt账户信息
	 * 
	 * @param bjc
	 *            币简称
	 * @param yhdz
	 *            平台地址
	 * @param ip
	 * @return
	 * @throws Throwable
	 *             2017年8月11日16:05:22
	 */
	@SuppressWarnings("rawtypes")
	public static BigDecimal getSwtYe(String bjc, String yhdz, String ip) throws SQLException {// 查询用户钱包信息
		StringBuffer u = new StringBuffer(ip).append("/v1/accounts/").append(yhdz).append("/balances")
				.append("?currency=").append(bjc).append("&counterparty=").append("");
		String res = HttpRequest.sendGet(u.toString());// 获取SWT钱包信息
		System.out.println(res + "SWT钱包信息");
		JSONObject jsonObject = JSONObject.fromObject(res.toString());
		Map<String, Class> classMap = new HashMap<String, Class>();
		classMap.put("balances", Balance.class);
		PtqbEntity ptzh = (PtqbEntity) JSONObject.toBean(jsonObject, PtqbEntity.class, classMap);
		BigDecimal ptzhze = new BigDecimal(ptzh.balances.get(0).value);
		BigDecimal ptzhdj = new BigDecimal(ptzh.balances.get(0).freezed);
		BigDecimal ye = ptzhze.subtract(ptzhdj);
		return ye;
	}

	/**
	 * 
	 * @param ip
	 * @param prot
	 *            端口
	 * @param username
	 *            用户名
	 * @param passS
	 *            密码
	 * @return
	 * @throws Throwable
	 *             2017年8月11日16:06:56
	 */
	public static BigDecimal getBtcYe(String ip, String prot, String username, String pass) throws SQLException {// 获取BTC系列账户信息
		BigDecimal ye = new BigDecimal(0);
		String s = "";
		try {
			s = post("getbalance", "[]", ip, prot, username, pass);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}

		Map<String, Object> reault_map = JsonUtil.GsonToMaps(s);
		if (reault_map != null && reault_map.containsKey("result")) {
			String reault_map_result = reault_map.get("result").toString();
			if (!StringHelper.isEmpty(reault_map_result)
					&& BigDecimalParser.parse(reault_map_result).compareTo(new BigDecimal(0)) > 0) {
				ye = BigDecimalParser.parse(reault_map_result);
			}
		} else {
			ye = BigDecimal.ZERO;
		}
		return ye;
	}
	
	public static String post(String method, String condition, String ip, String prot, String username, String pass)
			throws Exception {
		authenticator(username, pass);
		String result = "";
		String tonce = "" + (System.currentTimeMillis() * 1000);
		String url = "http://" + username + ":" + pass + "@" + ip + ":" + prot;
		URL obj = new URL(url);
		HttpURLConnection con = (HttpURLConnection) obj.openConnection();
		String userpass = pass;
		String basicAuth = "Basic" + DatatypeConverter.printBase64Binary(userpass.getBytes());
		con.setRequestMethod("POST");
		con.setRequestProperty("Json-Rpc-Tonce", tonce.toString());
		con.setRequestProperty("Authorization", basicAuth);
		String postdata = "{\"method\":\"" + method + "\", \"params\":" + condition + "}";
		con.setDoOutput(true);
		DataOutputStream wr = new DataOutputStream(con.getOutputStream());
		wr.writeBytes(postdata);
		wr.flush();
		wr.close();
		int responseCode = con.getResponseCode();
		if (responseCode != 200) {
			return "{\"result\":null,\"error\":" + responseCode + "}";
		}
		BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
		String inputLine;
		StringBuffer response = new StringBuffer();
		inputLine = in.readLine();
		response.append(inputLine);
		in.close();
		result = response.toString();
		return result;
	}

	/**
	 * 
	 * @throws SQLException
	 * @创建RPC链接 2017年8月9日16:21:13
	 */
	public static void authenticator(final String username, final String pass) throws SQLException {
		Authenticator.setDefault(new Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(username, pass.toCharArray());
			}
		});
	}
}